import moment from 'moment'
import {
  exportXls
} from '@/api/distribution/dataOverview'
import {
  exportXlsProfit
} from '@/api/distribution/positionsProfit'
import {
  exportXlsMonit
} from '@/api/distribution/monitoring'
import {
  exportXlsMain
} from '@/api/mainapi/mainapi'
import {
  exportFile
} from '@/utils/common.js'
import selectOptions from '@/utils/selectOptions.js'
export const mixin = {
  data: function () {
    return {
      dateType: true,
      umyTableIndex: 0,
      tableOptions: {},
      inTableOptions: {}
    }
  },
  methods: {
    // query的options
    deppCopyOptions() {
      this.tableOptions = JSON.parse(JSON.stringify(selectOptions))
      this.inTableOptions = JSON.parse(JSON.stringify(selectOptions))
      this.queryList.forEach(item => {
        if (item.label === '主体评级') item.options = this.tableOptions.issuerRatingOptions
        if (item.label === '债券类型') item.options = this.tableOptions.bondTypeOptions
        if (item.label === '投资人类型') item.options = this.tableOptions.investorType
        if (item.label === '负责人') item.options = this.tableOptions.person
      })
    },
    onReset() {
      this.$set(this.queryForm, 'date', [
        new Date().lastYear('yyyyMMdd'),
        new Date().format('yyyyMMdd')
      ])
      // Object.assign(this.$data, this.$options.data());
      this.getData()
    },
    saveTwo(str) {
      if (str === null || str === undefined || str === '') {
        return ''
      } else {
        const num = str + ''
        return Number(num).toFixed(2)
      }
    },
    avgSavetwo(str) {
      if (str === null || str === undefined || str === '') {
        return ''
      } else {
        const num = str + ''
        return Number(num).toFixed(2)
      }
    },
    dateChange(val) {
      if (val) {
        this.dateType = false
        this.$set(this.queryForm, 'date', val)
      } else {
        this.dateType = true
      }
    },
    dateBlur(e) {
      if (!this.dateType) return false
      const a1 = moment(e.refInput[0].value).format('yyyyMMDD')
      const a2 = moment(e.refInput[1].value).format('yyyyMMDD')
      this.$set(this.queryForm, 'date', [a1, a2])
    },
    // 去掉千分符
    strToNum(str) {
      // console.log(str, "str");
      let num = ''
      for (var i = 0; i < str.length; i++) {
        // console.log(str[i], "iiiii");
        if (str[i] != ',') {
          num += str[i]
        }
      }
      if (num == '') num = str
      return Number(num)
    },
    // 增加千分符
    formatMoney(s, q) {
      if (s == undefined || s == null) return 0.00
      s = Number(s).toFixed(2)
      var res = s.toString().replace(/\d+/, function (n) { // 先提取整数部分
        return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
          return $1 + ','
        })
      })
      return res
    },
    summaryMethod(params) {
      // console.log(params,'paramsSum');
      const noSummary = [
        'byyears',
        'issuerrating',
        'bondtype',
        'theleadunderwriter',
        'issuerperson',
        'principalheadperson',
        'issuerRating',
        'type',
        'leadunderwriter',
        'traderNm',
        'issuerNm',
        'isNbcbLeader',
        'branchNm',
        'ifLocatedInBranch',
        'underwriter',
        'uwRank'
      ]
      const {
        columns,
        data
      } = params
      const sums = []

      const moneyProperty = [
        'salescommission',
        'totalcommission',
        'alreadyreceivedsalescommission',
        'deservereceivedsalescommission',
        'commissionratio',
        'commission',
        'sumCommission',
        'commissionVer',
        'commissionDone',
        'totalIssueAmt',
        'totalAvgUwAmt',
        'mtnAmount',
        'scpAmt',
        'cpAmt',
        'ppnAmount',
        'abnAmount',
        'totalSettleQtty',
        'sumProfitEod',
        'totalProfitEod'
      ]
      const avgAndMax = [
        'avgHoldDays',
        'maxHoldDays'
      ]
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        // if (column.property == 'thecountofbond') {
        //     sums[index] = data[0].totalOfSec;
        // } else if (column.property == 'distributionamount') {
        //     sums[index] = data[0].totalDistributionamount;
        // } else if (column.property == 'salescommission') {
        //     sums[index] = data[0].totalCommission;
        // } else if (column.property == 'arithmeticaveragerate') {
        //     sums[index] = data[0].totalArithmeticaveragerate;
        // }
        if (noSummary.includes(column.property)) {
          sums[index] = ''
          return
        }
        const values = data.map(item => {
          if (moneyProperty.includes(column.property)) {
            return this.strToNum(item[column.property] ? item[column.property] : 0)
          } else {
            return Number(item[column.property])
          }
        })
        if (avgAndMax.includes(column.property)) {
          if (column.property == 'avgHoldDays') {
            let avgNum = 0
            values.forEach(item => {
              avgNum += item
            })
            // console.log();
            // console.log((avgNum / values.length).toFixed(2),'(avgNum / values.length).toFixed(2)');
            sums[index] = (avgNum / values.length).toFixed(2)
            return
          } else if (column.property == 'maxHoldDays') {
            sums[index] = Math.max(...values)
            return
          }
        }
        // console.log(values,column.property,index,'values');
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          // sums[index] += "元";
        } else {
          sums[index] = ''
        }
        // sums[index] = Number(sums[index]).toFixed(2);
        if (moneyProperty.includes(column.property)) {
          if (sums[index] == 0) {
            sums[index] = 0
          } else {
            sums[index] = this.formatMoney(sums[index], 2)
          }
        } else {
          sums[index] = this.saveTwo(Number(sums[index]))
          // sums[index] = sums[index];
        }
      })
      // return [sums];
      // console.log(sums,'sums');
      return sums
    },
    // 日期排序
    sortArr(array, key) {
      array.sort(function (a, b) {
        const x = new Date(a[key])
        const y = new Date(b[key])
        return x < y ? -1 : x > y ? 1 : 0
      })
      return array
      // console.log(array, 'array');
    },
    // 概览表格导出
    exportExcel(pageType, queryType, tableType, index) {
      // console.log(pageType, queryType, tableType);
      const func = [exportXlsMain, exportXls, exportXlsProfit, exportXlsMonit]
      const query = this.getQueryParams()
      delete query.page
      delete query.rows
      let params = {}

      if (index == 1) {
        // 代申购 代缴款 分销佣金 发行数据
        params = {
          query_type: queryType,
          export_type: tableType,
          ...query
        }
      } else if (index == 0 || index == 2 || index == 3) {
        // 主承业务概览 手续费收入 支出 fi和fi00持仓利润
        params = {
          exportFile: tableType,
          ...query
        }
      }

      // if (pageType == '代申购业务' || pageType == '代缴款业务' || pageType == '分销销售佣金分析') {
      //     if (this.checkConfig[0].checkSelect == "月") params.byMonth = "Y";
      //     if (this.checkConfig[0].checkSelect == "季") params.byQuarter = "Y";
      //     if (this.checkConfig[0].checkSelect == "年") params.byYear = "Y";
      //     params.effactiveDate_start = this.queryForm.date[0];
      //     params.effactiveDate_end = this.queryForm.date[1];
      //     this.tableColumns.forEach(item => {
      //         if (this.checkConfig[0].checkList.includes(item.label)) {
      //             if (item.label !== "时间") {
      //                 params[item.queryParams] = "Y";
      //             }
      //         }
      //     });
      // } else if (pageType == '发行数据分析') {
      //     params.effactiveDate_start = this.queryForm.date[0];
      //     params.effactiveDate_end = this.queryForm.date[1];
      // }
      // console.log(params);
      func[index](params).then(res => {
        // console.log(res);
        if (res) {
          const fileName = pageType + '概览.xls'
          exportFile(res.data, fileName, 'application/octet-stream')
        }
      })
    },
    getTablesort() {
      const sortArr = this.checkConfig[0].checkData.concat(this.checkConfig[1].checkData)
      const arr = []
      sortArr.forEach((item, index) => {
        this.tableColumns.forEach((item1, index1) => {
          if (item.label == item1.label) {
            this.$set(arr, index, item1)
          }
        })
      })
      arr.forEach((item, index) => {
        this.$set(this.tableColumns, index, item)
      })
      // console.log(this.tableColumns, 'this.tableColumns');
    },
    sortDate(arr) {
      arr.sort(function (a, b) {
        return moment(a.byyears).format('YYYYMMDD') < moment(b.byyears).format('YYYYMMDD') ? -1 : 1
      })
      return arr
    },
    // 分析维度 时间的下拉框 选择时自动勾选时间维度，其他维度同理
    selectChange(val) {
      const dateList = ['年', '季', '月'];
      const roleList = ['团员', '联席主承商']
      if (dateList.includes(val)) {
        if (!this.checkConfig[0].checkList.includes('时间')) {
          this.checkConfig[0].checkList.push('时间')
        }
      }
      if (roleList.includes(val)) {
        if (!this.checkConfig[0].checkList.includes('团内角色')) {
          this.checkConfig[0].checkList.push('团内角色')
        }
      }
      this.checkChange(this.checkConfig[0].checkList, '分析维度', this.checkConfig[0].checkList)
      this.getData()
    },
    selectChangeQuery(val, prop) {
      let options = []
      this.queryList.forEach(item => {
        if (item.prop == prop) {
          options = item.options
        }
      })
      options.forEach(item => {
        if (val.includes(item.value)) {
          item.checked = true
        } else {
          item.checked = false
        }
      })
    }
  }
}